<?php 
//miceCMS公用函数
if(!defined('IN_MICECMS')){header("HTTP/1.0 404 Not Found");die();}
define('_EMAIL_REGEX', "[\\w\\.\\-]+@(\\w+[\\w\\-]*\\.){1,}\\w{1,4}");

if (!function_exists('file_put_contents')) {	// PHP5
	function file_put_contents($path, $content) {
		$f = @fopen($path, 'wb');
		if ($f===false)
			return false;
		$amt = fwrite($f, $content);
		fclose($f);
		return $amt;
	}
}

if (!function_exists('stripos')) {	//PHP5
	function stripos($haystack, $needle, $offset = 0) {
		return strpos(strtolower($haystack), strtolower($needle), $offset);
	}
}

function RandomString($len) {
	static $salt = "abchefghj23kmnpqrstuvwxyz45ABCEFGH67JKMNPQRST89UVWXYZ";
	mt_srand((double)microtime()*1000000);
	$i = 0;
	$rand='';
	for ($i=0;$i<$len;$i++)
		$rand .= $salt[mt_rand(0, 32)];
	return $rand;
}

//判断是否有管理该模块的权限
function ModuleLimit($classname) {
	$miceSession = new session();
	$classnames=explode('_',$classname);
	if(!strstr($miceSession->get('groupmodule'),','.$classnames[0].','))
	{
		MessageBox('无操作权限',MICE_URL.'admin.php/index','您没有管理此模块的权限,请和总管理员联系');
		exit;
	}
	return 0;
}

//替换函数，只替换第一个满足条件的字符串
function StrReplaceOnce($search, $replace, $subject) {
	if (($p = strpos($subject, $search)) !== false)
		return substr($subject, 0, $p).$replace.substr($subject, $p + strlen($search));
	else
		return $subject;
}

function IsWritableFile($fname) {
	// 检查文件读写功能
	$rm = file_exists($fname);
	$f = @fopen($fname, 'a');
	if ($f===false)
		return false;
	fclose($f);
	if (!$rm)
		unlink($fname);
	return true;
}

function IsWritable($path) {
	if ($path[strlen($path)-1]=='/') // 递归返回临时文件路径
	    return IsWritableFile($path.uniqid(mt_rand()).'.tmp');
	else if (is_dir($path))
		return IsWritableFile($path.'/'.uniqid(mt_rand()).'.tmp');
	return IsWritableFile($path);
}

function _sql__recode($m) {
	$s = substr($m[0], 1, strlen($m[0])-2);
	if (!strlen($s)) return "''";
	return "'".str_replace("''", "'", $s)."'";
}

function _sql__recode_utf8($m) {
	$s = substr($m[0], 1, strlen($m[0])-2);
	if (!strlen($s)) return "''";
	return "'".utf8_encode(str_replace("''", "'", $s))."'";
}

function _sql__utf8($m) {
	$s = substr($m[0], 1, strlen($m[0])-2);
	if (!strlen($s)) return "''";
	return "'".utf8_encode($s)."'";
}

function SqlRecode(&$query, $fn) {
	return preg_replace_callback('/'.__QUOTED_S.'/', $fn, $query);
}

//分割sql语句
function SplitSQL(&$sql, $recode=false, $utf8=false) {
	if (preg_match_all("/(?i:select|update|insert into|delete|create|drop|alter|set)\\s+([^;']*('[^']*')*)*?(;|$)/",$sql, $m)) {
		if (MICE_DB=='gladius')
			$recode = false;
		if (!$recode && !$utf8)
			return $m[0];
		$n=array();
		$fn='_sql__';
		if ($recode) {
			$fn.='recode';
			if ($utf8){
				$fn.='_utf8';
			}
		} else {
			$fn.='utf8';
		}
		foreach($m[0] as $s) {
			$n[] = SqlRecode($s, $fn);
		}
		return $n;
	} else
		return array();
}

//判断是否是合法的IP v4地址
function is_ip($ipaddr){
	$ip=explode(".",$ipaddr);
	for($i=0;$i<4;$i++)  
	{  
		if($ip[$i]>255 OR !is_numeric($ip[$i]))
		{
			return 0;  
		}
	}
	return ereg("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$",$ipaddr);  
}


//判断用户真实ip
function GetRealIp() { 
	if ($_SERVER) { 
		if ( $_SERVER[HTTP_X_FORWARDED_FOR] ) { 
			$realip = $_SERVER["HTTP_X_FORWARDED_FOR"]; 
		} elseif ( $_SERVER["HTTP_CLIENT_IP"] ) { 
			$realip = $_SERVER["HTTP_CLIENT_IP"]; 
		} else { 
			$realip = $_SERVER["REMOTE_ADDR"]; 
		} 

	} else { 
		if ( getenv( 'HTTP_X_FORWARDED_FOR' ) ) { 
			$realip = getenv( 'HTTP_X_FORWARDED_FOR' ); 
		} elseif ( getenv( 'HTTP_CLIENT_IP' ) ) { 
			$realip = getenv( 'HTTP_CLIENT_IP' ); 
		} else { 
			$realip = getenv( 'REMOTE_ADDR' ); 
		} 
	}

	if(is_ip($realip)>0){
		return $realip;
	}else{
		return "0.0.0.0";
	}
}

//时间戳转换为时间
function Num2Time($micefun,$num){
	if($num<=0){
		$num=time();
	}
	$datetime = utf8_encode(strftime('%Y-%m-%d %H:%M:%S',$num));
	return $datetime;
}

//时间戳转换为日期
function Num2Date($micefun,$num){
	if($num<=0){
		$num=time();
	}
	$datetime = utf8_encode(strftime('%Y-%m-%d',$num));
	return $datetime;
}

//时间戳转换为日期
function Num2Date2($micefun,$num){
	if($num<=0){
		$num=time();
	}
	$datetime = utf8_encode(strftime('%m/%d',$num));
	return $datetime;
}

//时间转换为时间戳
function Time2Num($dtime){
	if(!ereg("[^0-9]",$dtime)){
		return $dtime;
	}
	$dtime = trim($dtime);
	$dt = Array(1970,1,1,0,0,0);
	$dtime = ereg_replace("[\r\n\t]|日|秒"," ",$dtime);
	$dtime = str_replace("年","-",$dtime);
	$dtime = str_replace("月","-",$dtime);
	$dtime = str_replace("时",":",$dtime);
	$dtime = str_replace("分",":",$dtime);
	$dtime = trim(ereg_replace("[ ]{1,}"," ",$dtime));
	$ds = explode(" ",$dtime);
	$ymd = explode("-",$ds[0]);
	if(!isset($ymd[1])){
		$ymd = explode(".",$ds[0]);
	}
	if(isset($ymd[0])){
		$dt[0] = $ymd[0];
	}
	if(isset($ymd[1])){
		$dt[1] = $ymd[1];
	}
	if(isset($ymd[2])){
		$dt[2] = $ymd[2];
	}
	if(strlen($dt[0])==2){
		$dt[0] = '20'.$dt[0];
	}
	if(isset($ds[1])){
		$hms = explode(":",$ds[1]);
		if(isset($hms[0])){
			$dt[3] = $hms[0];
		}
		if(isset($hms[1])){
			$dt[4] = $hms[1];
		}
		if(isset($hms[2])){
			$dt[5] = $hms[2];
		}
	}
	foreach($dt as $k=>$v){
		$v = ereg_replace("^0{1,}",'',trim($v));
		if($v==''){
			$dt[$k] = 0;
		}
	}
	$mt = @gmmktime($dt[3],$dt[4],$dt[5],$dt[1],$dt[2],$dt[0]) - 3600 * 8;
	if(!empty($mt)){
		return $mt;
	}else{
		return time();
	}
}

//获取文件扩展名
function FileExtName($file){
	$p = strrpos($file, '.');
	if ($p===false)return '';
	return strtolower(substr($file,$p+1));
}

//字符串重复函数
function StrRepeat($str,$num){
	$strs='';
	for($i=1;$i<=$num;$i++){
		$strs.=$str;
	}
	return $strs;
}

//获取系统配置的值 
function ConfigV($micefun,$tag){
	$config=new model_Config();
	$config->setSubsection('WHERE isuse=1 and tag=\''.$tag.'\'');
	$results=$config->doSelectOne();
	if($results){
		return $results->getValue();
	}else{
		return 0;
	}
}

//获取系统配置的附加值
function ConfigA($micefun,$tag){
	$config=new model_Config();
	$config->setSubsection('WHERE isuse=1 and tag=\''.$tag.'\'');
	$results=$config->doSelectOne();
	if($results){
		return $results->getAddedvalue();
	}else{
		return 0;
	}
}

//分类类别
function CategoryType() {
	$array = array(
	 'article0' => Array ( 
				'id' => 'article0',
				'name' =>'新闻文章',
		),
	'article1' => Array ( 
				'id' => 'article1',
				'name' =>'产品发布',
		),
	'article2' => Array ( 
				'id' => 'article2',
				'name' =>'文件下载',
		),
	'article3' => Array ( 
				'id' => 'article3',
				'name' =>'在线视频',
		),
	'article4' => Array ( 
				'id' => 'article4',
				'name' =>'人员招聘',
		),
	'article5' => Array ( 
				'id' => 'article5',
				'name' =>'其它',
		),
	);
	return $array;
}

//page导航条
function MicePager($totalpages,$totals,$pagenum,$listnum,$url){	
	//totalpages总页数,totals记录总数,pagenum当前页数，从1开始,lists导航条里显示多少页

	$listnum2 = ceil(($listnum-1)/2);
	if ($pagenum > $listnum2){
		if($listnum % 2 == 0)
			$pagenuma = $pagenum - $listnum2 + 1;
		else
			$pagenuma = $pagenum - $listnum2;

		$pagenumb = $pagenum + $listnum2;
	}
	else{
		$pagenuma = 1;
		$pagenumb = $listnum;
	}
	if ($pagenumb > $totalpages){
		if ($totalpages - $listnum + 1 > 0)
			$pagenuma = $totalpages - $listnum + 1;
		else
			$pagenuma = 1;

		$pagenumb = $totalpages;
	}

	if($pagenum > 1){
		$returns = "<a href='".$url."1'>首页</a> ";
		$returns .= "<a href='".$url.($pagenum - 1)."'>上一页</a> ";
	}
	for ($i = $pagenuma; $i <= $pagenumb; $i++){
		if ($i == $pagenum)
			$returns .= $i." ";
		else
			$returns .= "<a href='".$url.$i."'>".$i."</a> ";
	}
	if($pagenum < $totalpages){
		$returns .= "<a href='".$url.($pagenum + 1)."'>下一页</a> ";
		$returns .= "<a href='".$url.$totalpages."'>尾页</a>";
	}
	$returns .= ' '.$pagenum.'/'.$totalpages.'页 共'.$totals.'条记录';
	return $returns;
}

function MiceAddslashes($str){	//考虑过滤 字符串或数组，使用了 传归
	if(!is_array($str)) return addslashes($str);
	foreach($str as $key => $val) $str[$key] = MiceAddslashes($val);
	return $str;
}

function MiceStripslashes($str){	//考虑过滤 字符串或数组，使用了 传归
	if(!is_array($str)) return stripslashes($str);
	foreach($str as $key => $val) $str[$key] = MiceStripslashes($val);
	return $str;
}

// 替换逗号
function MiceFilterComma($str){
	$str = trim($str);
	$str = str_replace("，",",",$str);
	$str = str_replace(" ", ",", $str);
	$str = str_replace('　', ",", $str);
	return $str;
}

// 过滤引号
function MiceFilterQuote($str){
	$str = trim($str);
	$str = str_replace("'", "&#39", $str);
	$str = str_replace("'", "&#39", $str);
	$str = str_replace('\"', "&#34", $str);
	$str = str_replace('"', "&#34", $str);
	$str = str_replace(MICE_URL, "~__MICE_URL", $str);
	return $str;
}

//还原引号
function MiceRestoreQuote($micefun,$str) {
	$str = str_replace("&#34", '"', $str);
	$str = str_replace("\r\n", "", $str);
	$str = str_replace("~__MICE_URL", MICE_URL, $str);
	return $str;
}

//过滤html危险代码
function MiceFilterHtml($str){
	$str = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $str));
	return $str;
}

//清除html代码
function MiceClearHTML($micefun,$str){
	$str=strip_tags($str);
	$str=str_replace('　', '', $str);
	$str=str_replace(' ', '', $str);
	$rnstr = array("\r\n", "\n", "\r");
	$str=str_replace($rnstr,'',$str); 
	return $str; 
}

//获取List html文件路径
function GetHtmlPathList($cid,$lfn,$rule,$pid,$aid){
	$apath='list_{PID}.html';
	if(strlen($rule)){
		$apath=$rule;
	}

	$lpath=$cid;
	if(strlen($lfn)){
		$lpath=$lfn;
	}
	$lpath='list/'.$lpath.'/';
	if(!(file_exists($lpath) AND is_dir($lpath))){
		@mkdir($lpath,0777);
	}
	$apath=str_replace(array("{Y}","{M}","{D}","{TIMESTAMP}","{CID}","{PID}","{AID}"),array("","","","",$cid,$pid,$aid),$apath);
	$apath=$lpath.$apath;
	$apath2=substr($apath,0,stripos($apath,'.html')+5);
	$apath=str_replace('.html',MICE_HTML_EXT,$apath);
	$apath2=str_replace('.html',MICE_HTML_EXT,$apath2);
	
	if(!IsWritable(MICE_DIR.$apath2)){
		return false;
	}
	return $apath;
}

//获取Article html文件路径
function GetHtmlPathArticle($cid,$lfn,$rule,$aid,$fn,$createdat){
	$apath='article_{AID}.html';
	if(strlen($fn)){
		$apath=$fn;
	}elseif(strlen($rule)){
		$apath=$rule;
	}

	$lpath=$cid;
	if(strlen($lfn)){
		$lpath=$lfn;
	}
	$lpath='article/'.$lpath.'/';
	if(!(file_exists($lpath) AND is_dir($lpath))){
		@mkdir($lpath,0777);
	}
	$y=utf8_encode(strftime('%Y',$createdat));
	$m=utf8_encode(strftime('%m',$createdat));
	$d=utf8_encode(strftime('%d',$createdat));
	$apath=str_replace(array("{Y}","{M}","{D}","{TIMESTAMP}","{CID}","{AID}"),array($y,$m,$d,$createdat,$cid,$aid),$apath);
	$apath=$lpath.$apath;
	$apath=str_replace('.html',MICE_HTML_EXT,$apath);
	if(!IsWritable(MICE_DIR.$apath)){
		return false;
	}	
	return $apath;
}

//获得首页\友情链接列表\网站地图的URL
function GetUrl($micefun,$type){
	$miceSession = new session();
	if(MICE_HTML==1 AND (is_file(MICE_DIR.$type.MICE_HTML_EXT) OR $miceSession->get('makehtml')=='miceCMS')){
		return MICE_URL.$type.MICE_HTML_EXT;
	}
	return MICE_URL.MICE_REWRITE.$type.MICE_HTML_EXT;
}

//获得分类列表的URL
function ListUrl($micefun,$cid,$pid='1',$aid=''){
	$miceSession = new session();
	$category=new model_Category();
	$category->setSubsection('WHERE category_id='.$cid);
	$CategoryRS=$category->doSelectOne();

	$url=GetHtmlPathList($CategoryRS->getCategoryId(),$CategoryRS->getFilename(),$CategoryRS->GetListrule(),$pid,$aid);
	$url0=substr($url,0,stripos($url,MICE_HTML_EXT)+strlen(MICE_HTML_EXT));

	if(MICE_HTML==1){
		if(is_file(MICE_DIR.$url0) OR $miceSession->get('makehtml')=='miceCMS'){
			return MICE_URL.$url;
		}
	}
	return MICE_URL.MICE_REWRITE.$url;
}

//获得分类封面的URL
function ChannelUrl($micefun,$cid){
	$miceSession = new session();
	$category=new model_Category();
	$category->setSubsection('WHERE category_id='.$cid);
	$CategoryRS=$category->doSelectOne();

	$lpath=$CategoryRS->getCategoryId();
	if(strlen($CategoryRS->getFilename())){
		$lpath=$CategoryRS->getFilename();
	}

	if(MICE_HTML==1){
		if(is_file(MICE_DIR.'channel/'.$lpath.MICE_HTML_EXT) OR $miceSession->get('makehtml')=='miceCMS'){
			return MICE_URL.'channel/'.$lpath.MICE_HTML_EXT;
		}
	}
	return MICE_URL.MICE_REWRITE.'channel/'.$lpath.MICE_HTML_EXT;
}

//获得文档的URL
function ArticleUrl($micefun,$cid,$aid){
	$miceSession = new session();
	if(!is_numeric($cid)){
			$cid=CategoryId('micefun',$cid);
		}

	$category=new model_Category();
	$category->setSubsection('WHERE category_id='.$cid);
	$CategoryRS=$category->doSelectOne();

	$article=new model_Article();
	$article->setSubsection('WHERE article_id='.$aid);
	$ArticleRS=$article->doSelectOne();

	$url=GetHtmlPathArticle($CategoryRS->getCategoryId(),$CategoryRS->getFilename(),$CategoryRS->GetArticlerule(),$ArticleRS->getArticleId(),$ArticleRS->getFilename(),$ArticleRS->getCreatedat());

	if(MICE_HTML==1){
		if(is_file(MICE_DIR.$url) OR $miceSession->get('makehtml')=='miceCMS'){
			return MICE_URL.$url;
		}
	}
	return MICE_URL.MICE_REWRITE.$url;
}


//********************************以下函数均用于字符串截取***************************
//字符串截取函数
//要处理的字符串,长度(即字数),在被截取过字符串后边加上的字符串(...等)
function MiceCutStr($micefun,$content,$maxlen=300,$str){
	//$content=MiceRestoreQuote('micefun',$content);
	//把字符按HTML标签变成数组。
	$content = preg_split("/(<[^>]+?>)/si",$content, -1,PREG_SPLIT_NO_EMPTY| PREG_SPLIT_DELIM_CAPTURE);
	$wordrows=0;	//中英字数
	$outstr="";	  //生成的字串
	$wordend=false;	//是否符合最大的长度
	$beginTags=0;	//除<img><br><hr>这些短标签外，其它计算开始标签，如<div*>
	$endTags=0;	  //计算结尾标签，如</div>，如果$beginTags==$endTags表示标签数目相对称，可以退出循环。
	//print_r($content);
	foreach($content as $value){
	  if (trim($value)=="") continue;	//如果该值为空，则继续下一个值

	  if (strpos(";$value","<")>0){
		 //如果与要载取的标签相同，则到处结束截取。
		 if (trim($value)==$maxlen) {
			$wordend=true;
			continue;
		 }

		 if ($wordend==false){
			$outstr.=$value;
			if (!preg_match("/<img([^>]+?)>/is",$value) && !preg_match("/<param([^>]+?)>/is",$value) && !preg_match("/<!([^>]+?)>/is",$value) && !preg_match("/<br([^>]+?)>/is",$value) && !preg_match("/<hr([^>]+?)>/is",$value)) {
			  $beginTags++; //除img,br,hr外的标签都加1
			}
		 }else if (preg_match("/<\/([^>]+?)>/is",$value,$matches)){
			$endTags++;
			$outstr.=$value;
			if ($beginTags==$endTags && $wordend==true) break;	//字已载完了，并且标签数相称，就可以退出循环。
		 }else{
			if (!preg_match("/<img([^>]+?)>/is",$value) && !preg_match("/<param([^>]+?)>/is",$value) && !preg_match("/<!([^>]+?)>/is",$value) && !preg_match("/<br([^>]+?)>/is",$value) && !preg_match("/<hr([^>]+?)>/is",$value)) {
			  $beginTags++; //除img,br,hr外的标签都加1
			  $outstr.=$value;
			}
		 }
	  }else{
		 if (is_numeric($maxlen)){	//截取字数
			$curLength=MiceStrLen($value);
			$maxLength=$curLength+$wordrows;
			if ($wordend==false){
			  if ($maxLength>$maxlen){	//总字数大于要截取的字数，要在该行要截取
				 $outstr.=MiceSubString($value,0,$maxlen-$wordrows);
				 $wordend=true;
			  }else{
				 $wordrows=$maxLength;
				 $outstr.=$value;
			  }
			}
		 }else{
			if ($wordend==false) $outstr.=$value;
		 }
	  }
	}
	//循环替换掉多余的标签，如<p></p>这一类
	while(preg_match("/<([^\/][^>]*?)><\/([^>]+?)>/is",$outstr)){
	  $outstr=preg_replace_callback("/<([^\/][^>]*?)><\/([^>]+?)>/is","MiceStripEmptyHtml",$outstr);
	}
	//把误换的标签换回来
	if (strpos(";".$outstr,"[html_")>0){
	  $outstr=str_replace("[html_<]","<",$outstr);
	  $outstr=str_replace("[html_>]",">",$outstr);
	}
	if ($wordend==true) $outstr.=$str;
	return $outstr;
}

//去掉多余的空标签
function MiceStripEmptyHtml($matches){
	$arr_tags1=explode(" ",$matches[1]);
	if ($arr_tags1[0]==$matches[2]){	//如果前后标签相同，则替换为空。
	  return "";
	}else{
	  $matches[0]=str_replace("<","[html_<]",$matches[0]);
	  $matches[0]=str_replace(">","[html_>]",$matches[0]);
	  return $matches[0];
	}
}

//取得字符串的长度，包括中英文。
function MiceStrLen($text){
	if (function_exists('mb_substr')) {
	  $length=mb_strlen($text,'UTF-8');
	} elseif (function_exists('iconv_substr')) {
	  $length=iconv_strlen($text,'UTF-8');
	} else {
	  preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $text, $ar);
	  $length=count($ar[0]);

	}
	return $length;
}

/***********按一定长度截取字符串（包括中文）*********/
function MiceSubString($text, $start=0, $limit=12) {
	if (function_exists('mb_substr')) {
	  $more = (mb_strlen($text,'UTF-8') > $limit) ? TRUE : FALSE;
	  $text = mb_substr($text, 0, $limit, 'UTF-8');
	  return $text;
	} elseif (function_exists('iconv_substr')) {
	  $more = (iconv_strlen($text,'UTF-8') > $limit) ? TRUE : FALSE;
	  $text = iconv_substr($text, 0, $limit, 'UTF-8');
	  //return array($text, $more);
	  return $text;
	} else {
	  preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $text, $ar);
	  if(func_num_args() >= 3) {
		 if (count($ar[0])>$limit) {
			$more = TRUE;
			$text = join("",array_slice($ar[0],0,$limit));
		 } else {
			$more = FALSE;
			$text = join("",array_slice($ar[0],0,$limit));
		 }
	  } else {
		 $more = FALSE;
		 $text = join("",array_slice($ar[0],0));
	  }
	  return $text;
	}
}
?>